﻿using System;
using System.ComponentModel.Design;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.Shell;
using PS_WSSDeploy_Package.Application;
using PS_WSSDeploy_Package.Utils;
using PS_WSSDeploy_Package.WSPBuilder;

namespace PS_WSSDeploy_Package.WdCommand
{
    class BuildCmd : BaseCmd, IWdTask
    {
        public static BaseCmd Create(OleMenuCommandService service, bool enableForSandbox)
        {
            var instance = new BuildCmd();
            var cmdId = new CommandID(GuidList.guidPS_WSSDeploy_PackageCmdSet, (int)PkgCmdIDList.cmdidBuildCommand);
            AddCommandToMenu(service, instance, cmdId, enableForSandbox);
            return instance;
        }

        public override void DoExecute()
        {
            if (IsSharePointProject)
            {
                BuildPackage();
            }
            else
            {
                var wspCmdLine = new StringBuilder(string.Format("-BuildWSP true -WSPName {0} ", WSPFileName));

                if (!ActiveConfig.UseTargetPath)
                {
                    wspCmdLine.Append(string.Format(
                        " -Excludepaths \"{0}\""
                        , Path.GetDirectoryName(ProjectTargetPath)));
                }

                AddTask(new WSPBuildTask(ProjectPath, wspCmdLine.ToString()));
            }
        }

        public override bool DoCheckExistConfig()
        {
            return true;
        }

        public override void DoPreExecute()
        {
            if (!IsSharePointProject)
            {
                Build();
            }
            base.DoPreExecute();
        }

        public override void DoPostExecute()
        {
            if(!IsSharePointProject)
            {
                base.DoPostExecute();
            }
        }

        public void TaskExecute()
        {
            try
            {
                Build();

                if (IsSharePointProject)
                {
                    BuildPackage();
                }
                else
                {
                    var wspCmdLine = new StringBuilder(string.Format("-BuildWSP true -WSPName {0} ", WSPFileName));

                    if (!ActiveConfig.UseTargetPath)
                    {
                        wspCmdLine.Append(string.Format(
                            " -Excludepaths \"{0}\""
                            , Path.GetDirectoryName(ProjectTargetPath)));
                    }

                    var buildTask = new WSPBuildTask(ProjectPath, wspCmdLine.ToString());
                    buildTask.TaskExecute();
                }
                SetSuccess();
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format(WssDeployResources.BuildCmd_BuildError, WSPFileName, ex.Message));
                SetFailed();
            }
        }
    }
}
